package com.yuan.zsschool.ui.account;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.BaseUserManager;
import com.yuan.base.framework.bean.TeachClass;
import com.yuan.base.framework.bean.TeachSchool;
import com.yuan.base.framework.bean.TipResult;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.utils.DialogUtil;
import com.yuan.base.utils.PreferencesUtils;
import com.yuan.zsschool.AppContext;
import com.yuan.zsschool.Constant;
import com.yuan.zsschool.R;
import com.yuan.zsschool.Urls;
import com.yuan.zsschool.bean.Grade;
import com.yuan.zsschool.bean.School;
import com.yuan.zsschool.ui.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 教师绑定
 */
public class ApplyTeachBindingActivity extends BaseFrameworkActivity {

	private TextView tv_title;
	private LinearLayout ll_user_info;
	private EditText et_name;
	private EditText et_id_card;
	private TextView tv_sex;
	private TextView tv_garden;
	private TextView tv_target_school;
	private TextView tv_target_class;
	private List<School> schoolList;
	private List<Grade> gradeList;
	private School selectSchool;
	private String selectGrade;
	private boolean[] selectGradeFlag;

	// 过滤已选择的
	private ArrayList<Integer> filter = new ArrayList<>();
	private boolean isApplyFirst = true;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_apply_teach;
	}

	@Override
	protected void bindViews() {
		tv_title = findViewById(R.id.tv_title);
		ll_user_info = findViewById(R.id.ll_user_info);
		et_name = findViewById(R.id.et_name);
		et_id_card = findViewById(R.id.et_id_card);
		tv_sex = findViewById(R.id.tv_sex);
		tv_garden = findViewById(R.id.tv_garden);
		tv_target_school = findViewById(R.id.tv_target_school);
		tv_target_class = findViewById(R.id.tv_target_class);

		tv_sex.setOnClickListener(v -> selectSex());
		tv_garden.setOnClickListener(v -> selectGarden());

		setOnClickListener(R.id.ll_target_school, v -> {
			if (!isApplyFirst) {
				return;
			}
			if (gradeList == null) {
				BaseHttpRequest.get(Urls.getUrl(Urls.getAllSchool), new BaseHttpCallBack<JSONObject>() {
					@Override
					public void onPost() {
						hideProgressBar();
					}

					@Override
					public void onPreStart() {
						showProgressBar("正在加载数据");
					}

					@Override
					public void onSuccess(JSONObject result) {
						schoolList = JSON.parseArray(result.getString("content"), School.class);
						showSelectSchool(schoolList);
					}
				});
			} else {
				showSelectSchool(schoolList);
			}
		});

		setOnClickListener(R.id.ll_target_class, v -> {
			if (selectSchool == null) {
				showToast("请先选择学校");
				return;
			}
			if (gradeList == null) {
				HashMap<String, Object> params = new HashMap<>();
				params.put("school", selectSchool.getId());
				BaseHttpRequest.get(Urls.getUrl(Urls.getGradeById), params, new BaseHttpCallBack<JSONObject>() {
					@Override
					public void onPost() {
						hideProgressBar();
					}

					@Override
					public void onPreStart() {
						showProgressBar("正在加载数据");
					}

					@Override
					public void onSuccess(JSONObject result) {
						gradeList = JSON.parseArray(result.getString("content"), Grade.class);
						showSelectClass(gradeList);
					}
				});
			} else {
				showSelectClass(gradeList);
			}
		});
		setOnClickListener(R.id.btn_submit, v -> doSubmit());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		isApplyFirst = BaseUserManager.getUser() == null;
		if (!isApplyFirst) {
			tv_title.setText("权限申请");
			ll_user_info.setVisibility(View.GONE);
			List<TeachSchool> teachSchoolList = AppContext.getPermission();
			for (int i = 0; i < teachSchoolList.size(); i++) {
				List<TeachClass> teachClassList = teachSchoolList.get(i).getClass_all();
				for (int j = 0; j < teachClassList.size(); j++) {
					filter.add(teachClassList.get(j).getClassIds());
				}
			}
			tv_target_school.setText(teachSchoolList.get(0).getSchoolName());
			selectSchool = new School();
			selectSchool.setId(teachSchoolList.get(0).getSchoolId());
			selectSchool.setName(teachSchoolList.get(0).getSchoolName());
		}
	}

	private void showSelectSchool(List<School> schoolList) {
		String[] schools = new String[schoolList.size()];
		for (int i = 0; i < schoolList.size(); i++) {
			schools[i] = schoolList.get(i).getName();
		}
		DialogUtil.select(this, "选择学校", schools, (dialog, which) -> {
			tv_target_school.setText(schools[which]);
			selectSchool = schoolList.get(which);
			gradeList = null;
			tv_target_class.setText("");
			selectGrade = "";
			selectGradeFlag = null;
		});
	}

	private void showSelectClass(List<Grade> gradeList) {
		for (int i = gradeList.size() - 1; i >= 0; i--) {
			if (filter.contains(gradeList.get(i).getId())) {
				gradeList.remove(i);
			}
		}

		String[] schools = new String[gradeList.size()];
		if (selectGradeFlag == null) {
			selectGradeFlag = new boolean[gradeList.size()];
			for (int i = 0; i < gradeList.size(); i++) {
				selectGradeFlag[i] = false;
			}
		}
		for (int i = 0; i < gradeList.size(); i++) {
			schools[i] = gradeList.get(i).getName();
		}
		if (isApplyFirst) {
			DialogUtil.selectMulti(this, "选择班级", schools, selectGradeFlag, null, "确定", (dialog, which) -> {
				selectGrade = "";
				String temp = "";
				int max = 3;
				for (int i = 0; i < selectGradeFlag.length; i++) {
					if (selectGradeFlag[i]) {
						selectGrade += gradeList.get(i).getId() + ",";
						temp += gradeList.get(i).getName() + ",";
						max--;
						if (max <= 0) {
							break;
						}
					}
				}
				if (selectGrade.length() > 0) {
					selectGrade = selectGrade.substring(0, selectGrade.length() - 1);
					temp = temp.substring(0, temp.length() - 1);
				}
				tv_target_class.setText(temp);
			}, "取消", null);
		} else {
			DialogUtil.select(this, "选择班级", schools, (dialog, which) -> {
				selectGrade = String.valueOf(gradeList.get(which).getId());
				tv_target_class.setText(gradeList.get(which).getName());
			}, "取消", null);
		}
	}

	@Override
	public void closeSelf() {
		if (BaseUserManager.getUser() == null) {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		super.closeSelf();
	}

	private void selectSex() {
		String[] sex = new String[]{"男", "女"};
		DialogUtil.select(this, "选择性别", sex, (dialog, which) -> tv_sex.setText(sex[which]));
	}

	private void selectGarden() {
		String[] garden = new String[]{"是", "否"};
		DialogUtil.select(this, "选择是否认证园长", garden, (dialog, which) -> {
			tv_garden.setText(garden[which]);
			if (which == 0) {
				((View) tv_target_class.getParent()).setVisibility(View.GONE);
			} else {
				((View) tv_target_class.getParent()).setVisibility(View.VISIBLE);
			}
		});
	}

	private void doSubmit() {
		String url = Urls.getUrl(Urls.applyTeacherBinding);
		HashMap<String, Object> params = new HashMap<>();
		if (!isApplyFirst) {
			url = Urls.getUrl(Urls.applyIdentity);
			params.put("classId", selectGrade);
		} else {
			if (TextUtils.isEmpty(getStringTrimByUI(et_name))) {
				showToast("请填写姓名");
				return;
			}
			if (TextUtils.isEmpty(getStringTrimByUI(et_id_card))) {
				showToast("请填写身份证");
				return;
			}
			params.put("name", getStringTrimByUI(et_name));
			params.put("idCardNo", getStringTrimByUI(et_id_card));
			params.put("gender", getStringTrimByUI(tv_sex));
			if (selectSchool == null) {
				showToast("请选择任教学校");
				return;
			}
			// 是否认证园长
			if (isGarden()) {
				params.put("master", true);
				url = Urls.getUrl(Urls.applyGardenBinding);
				params.put("schoolId", selectSchool.getId());
			} else {
				if (TextUtils.isEmpty(selectGrade)) {
					showToast("请选择任教班级");
					return;
				}
				params.put("master", false);
				String[] cls = selectGrade.split(",");
				if (cls.length > 0) {
					params.put("classId1", cls[0]);
				}
				if (cls.length > 1) {
					params.put("classId2", cls[1]);
				}
				if (cls.length > 2) {
					params.put("classId3", cls[2]);
				}
			}
		}
		params.put("phone1", PreferencesUtils.getString(this, Constant.Preferences.USER_CODE, ""));

		BaseHttpRequest.post(url, params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onPost() {
				hideProgressBarAtOnce();
			}

			@Override
			public void onPreStart() {
				showProgressBar("正在提交...");
			}

			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					showToast("申请成功");
					closeSelf();
				} else {
					showToast(result.getMessage());
				}
			}
		});
	}

	private boolean isGarden() {
		return getStringTrimByUI(tv_garden).equals("是");
	}

}
